package com.miya.demo.common.util;

import org.owasp.esapi.ESAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


/**
 * es api工具类
 *
 * @author CaiXiaowei
 * @date 2022/09/05
 */
public class EsApiUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(EsApiUtil.class);

    public static <T> T encodeForHtml(T t) {
        try {
            SerializeUtil.serializeToObject(EsApiUtil.encode(SerializeUtil.serialize(t)), t);
        } catch (IOException e) {
            LOGGER.warn("XSS error",e.getStackTrace());
        } catch (ClassNotFoundException e) {
            LOGGER.warn("XSS error",e.getStackTrace());
        }
        // filter xss
        return t;
    }

    private static String encode(String value) {
        return ESAPI.encoder().encodeForHTML(ESAPI.encoder().encodeForJavaScript(ESAPI.encoder().canonicalize(value)));
    }

}